package com.linln.admin.business.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.vo.ResultVo;
import com.linln.modules.business.domain.Salary;
import com.linln.modules.business.service.impl.SalaryServiceImpl;
import com.linln.modules.system.domain.User;
import com.linln.modules.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


/**
 * @author 小懒虫
 * @date 2021/11/13
 */
@Controller
@RequestMapping("/business/salary")
public class SalaryController {

    @Autowired
    private SalaryServiceImpl salaryService;
    @Autowired
    private UserService userService;

    /**
     * 列表页面
     */
    @GetMapping("/index")
    public String index(Model model, Salary salary) {

        IPage<Salary> page = salaryService.getMySalaryDetail(salary);
        model.addAttribute("list", page.getRecords());
        model.addAttribute("page", page);
        return "/business/salary/index";
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    public String toAdd(HttpServletRequest request, Model model) {
        String payDateStr = request.getParameter("payDateStr");
        model.addAttribute("payDateStr", payDateStr);
        return "/business/salary/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    public String toEdit(@PathVariable("id") String salaryId, Model model) {
        Salary salary = salaryService.getById(salaryId);
        model.addAttribute("salary", salary);
        return "/business/salary/add";
    }

    /**
     * 保存添加/修改的数据
     */
    @PostMapping("/save")
    @ResponseBody
    public ResultVo save(Salary salary) {
        Long userId = salary.getUserId();
        User user = userService.getById(userId);
        if (StringUtils.isEmpty(user)) {
            return ResultVoUtil.error("用户ID不存在");
        }
        salary.setUserName(user.getUsername());
        salaryService.saveOrUpdate(salary);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/delete/{id}")
    @ResponseBody
    public ResultVo delSalary(@PathVariable("id") String id) {
        salaryService.delSalary(id);
        return ResultVoUtil.success("删除成功");
    }

}